package com.frame.jfinal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;

import com.jfinal.aop.Interceptor;
import com.jfinal.core.ActionInvocation;
import com.jfinal.core.Controller;
import com.system.model.User;
import com.weixin.model.AppUser;

/**
 * @author LRC
 * @createDate 2015年5月19日
 * @description 全局变量拦截器，编写全局处理代码
 */
public class GlobalInterceptor implements Interceptor{
	
	
	public void intercept(ActionInvocation ai) {
		//全局处理器处理
		Controller c = ai.getController();
		HttpServletResponse response = c.getResponse();
		//设置支持跨域
		response.setHeader("Access-Control-Allow-Origin", "*");
		//将用户信息添加到页面中
		Object user = c.getSession().getAttribute("user");
		if(user!=null){
			c.setAttr("user", user);
			//当前线程绑定user对象
			User.setCurrentUser(user);
		}
		
		//绑定微信账号
		Object appUser = c.getSession().getAttribute("appUser");
		if(appUser!=null){
			c.setAttr("appUser", appUser);
			//当前线程绑定user对象
			AppUser.setCurrentUser(appUser);
		}
		
		//打印返回这Ip
		HttpServletRequest request = c.getRequest();
		String ip = request.getHeader("x-forwarded-for");
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getHeader("WL-Proxy-Client-IP");
	    }
	    if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)){
	        ip = request.getRemoteAddr();
	    }
	    ip = ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1":ip;
	    
		Integer port = c.getRequest().getRemotePort();
		String remoteuser = c.getRequest().getRemoteUser();
		System.out.println(String.format("remoteuser=%s,host=%s:%d", remoteuser,ip,port));
		//调用后台方法
		ai.invoke();

	}

}
